/**
 * 货币格式化和转换工具类
 */

export interface CurrencyFormatOptions {
  locale?: string
  currency?: string
  minimumFractionDigits?: number
  maximumFractionDigits?: number
  notation?: 'standard' | 'scientific' | 'engineering' | 'compact'
}

class CurrencyUtils {
  /**
   * 格式化韩元显示
   */
  formatKRW(amount: number, options?: CurrencyFormatOptions): string {
    const defaultOptions: CurrencyFormatOptions = {
      locale: 'ko-KR',
      currency: 'KRW',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
      ...options
    }

    try {
      return new Intl.NumberFormat(defaultOptions.locale, {
        style: 'currency',
        currency: defaultOptions.currency,
        minimumFractionDigits: defaultOptions.minimumFractionDigits,
        maximumFractionDigits: defaultOptions.maximumFractionDigits,
        notation: defaultOptions.notation
      }).format(amount)
    } catch (error) {
      console.error('통화 포맷 실패:', error)
      return `₩${this.formatNumber(amount)}`
    }
  }

  /**
   * 格式化数字显示（添加千位分隔符）
   */
  formatNumber(num: number, locale: string = 'ko-KR'): string {
    try {
      return new Intl.NumberFormat(locale).format(num)
    } catch (error) {
      console.error('숫자 포맷 실패:', error)
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
  }

  /**
   * 格式化简化数字显示（如 1.2M, 5.8K）
   */
  formatCompactNumber(num: number, locale: string = 'ko-KR'): string {
    try {
      return new Intl.NumberFormat(locale, {
        notation: 'compact',
        maximumFractionDigits: 1
      }).format(num)
    } catch (error) {
      console.error('숫자 단순화 포맷 실패:', error)
      if (num >= 1000000000) {
        return `${(num / 1000000000).toFixed(1)}B`
      } else if (num >= 1000000) {
        return `${(num / 1000000).toFixed(1)}M`
      } else if (num >= 1000) {
        return `${(num / 1000).toFixed(1)}K`
      }
      return num.toString()
    }
  }

  /**
   * 计算价格变化百分比
   */
  calculateChangeRate(currentPrice: number, previousPrice: number): number {
    if (previousPrice === 0) return 0
    return ((currentPrice - previousPrice) / previousPrice) * 100
  }

  /**
   * 格式化百分比显示
   */
  formatPercentage(rate: number, includeSign: boolean = true): string {
    const sign = includeSign ? (rate > 0 ? '+' : '') : ''
    return `${sign}${rate.toFixed(2)}%`
  }

  /**
   * 格式化价格变化显示（含颜色类）
   */
  formatPriceChange(changePrice: number, changeRate: number): {
    priceText: string
    percentageText: string
    colorClass: string
    icon: string
  } {
    const priceText = this.formatKRW(Math.abs(changePrice))
    const percentageText = this.formatPercentage(changeRate)
    
    let colorClass = 'neutral'
    let icon = '='
    
    if (changePrice > 0) {
      colorClass = 'positive'
      icon = '▲'
    } else if (changePrice < 0) {
      colorClass = 'negative'
      icon = '▼'
    }

    return {
      priceText,
      percentageText,
      colorClass,
      icon
    }
  }

  /**
   * USD转KRW（使用模拟汇率）
   */
  convertUSDToKRW(usdAmount: number, exchangeRate: number = 1330): number {
    return Math.round(usdAmount * exchangeRate)
  }

  /**
   * 计算NEAR代币价值
   */
  calculateNearValue(nearAmount: number, nearPriceKRW: number): number {
    return Math.round(nearAmount * nearPriceKRW)
  }

  /**
   * 格式化代币数量显示
   */
  formatTokenAmount(amount: number, symbol: string, decimals: number = 2): string {
    return `${amount.toFixed(decimals)} ${symbol}`
  }

  /**
   * 获取价格变化的颜色类名
   */
  getPriceChangeColor(change: number): string {
    if (change > 0) return 'text-green-600'
    if (change < 0) return 'text-red-600'
    return 'text-gray-600'
  }

  /**
   * 计算年化收益率
   */
  calculateAPY(principal: number, rewards: number, days: number): number {
    if (principal === 0 || days === 0) return 0
    const dailyRate = rewards / principal / days
    const apy = (Math.pow(1 + dailyRate, 365) - 1) * 100
    return Math.round(apy * 100) / 100
  }

  /**
   * 格式化时间显示
   */
  formatTimeAgo(timestamp: number): string {
    const now = Date.now()
    const diff = now - timestamp
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days > 0) {
      return `${days}일 전`
    } else if (hours > 0) {
      return `${hours}시간 전`
    } else if (minutes > 0) {
      return `${minutes}분 전`
    } else {
      return '방금 전'
    }
  }
}

// 导出单例实例
export const currencyUtils = new CurrencyUtils()

// 导出常用的格式化函数
export const {
  formatKRW,
  formatNumber,
  formatCompactNumber,
  calculateChangeRate,
  formatPercentage,
  formatPriceChange,
  convertUSDToKRW,
  calculateNearValue,
  formatTokenAmount,
  getPriceChangeColor,
  calculateAPY,
  formatTimeAgo
} = currencyUtils